import json

from django.forms import model_to_dict

from django import forms
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from app01 import models

from datetime import datetime
from app01.utils.pagination import pagination


def staff_list(request):
    return render(request, 'staff_list.html')


# 处理数据
def staff_list_clean(staff_list_data):
    for i in staff_list_data:
        i['level'] = models.StaffInfo.level_choices[i['level'] - 1][1]
        if i['team_id']:
            i['team_id'] = models.Team.objects.filter(id=i['team_id']).values('name').first()['name']
        else:
            i['team_id'] = '无'
        i['secondary_structure']=models.secondary_structure.objects.filter(id=i['secondary_structure_id']).values('name').first()['name']
        # 调用staffInfo表中的calculate_staff_score方法
        i['staff_score'] = models.StaffInfo.objects.filter(id=i['id']).first().calculate_staff_score()



def staff_post(request):
    res = {
        'status': True,
        'staff_list_data': None,
    }
    if request.method == 'GET':
        if request.tracer.level == 2:
            team_id = request.tracer.team_id
            staff_list = models.StaffInfo.objects.filter(team_id=team_id)

        else:
            staff_list = models.StaffInfo.objects.all().order_by('team')
        # 获取所有员工的数据

        staff_list_data = list(staff_list.values())
        print('staff_list_data', staff_list_data)
        staff_list_clean(staff_list_data)

        res['staff_list_data'] = staff_list_data

        return JsonResponse(res)


def staff_export_excel(request):
    """导出数据到excel"""
    if request.method == 'GET':
        # 获取所有员工的数据
        staff_list = models.StaffInfo.objects.all().order_by('team')

        staff_list_data = list(staff_list.values())

        staff_list_clean(staff_list_data)

        # 生成excel
        import xlwt
        # 创建工作簿
        workbook = xlwt.Workbook(encoding='utf-8')
        # 创建工作表
        worksheet = workbook.add_sheet('员工信息表')
        #获取所有的字段
        fields=models.StaffInfo._meta.fields
        #获取所有的字段名verbose_name
        fields_name=[field.verbose_name for field in fields]

        fields_name.remove('ID')
        fields_name.remove('员工密码')
        fields_name.remove('已签约客户数量')
        print(fields_name)
        # 将所有字段信息写入表头
        for i in range(len(fields_name)):
            worksheet.write(0,i,fields_name[i])



        # 写入数据
        for i, staff in enumerate(staff_list_data):
            worksheet.write(i + 1, 0, staff['staff_num'])
            worksheet.write(i + 1, 1, staff['name'])
            worksheet.write(i + 1, 2, staff['level'])
            worksheet.write(i + 1, 3, staff['secondary_structure'])
            worksheet.write(i + 1, 4, staff['team_id'])
            worksheet.write(i + 1, 5, staff['customer_count'])
            worksheet.write(i + 1, 6, staff['financial_product_count'])
            worksheet.write(i + 1, 7, staff['fund_products_count'])
            worksheet.write(i + 1, 8, staff['investment_assets_count'])
            worksheet.write(i + 1, 9, staff['add_weChat_count'])
            worksheet.write(i + 1, 10, staff['contract_stock_count'])
            worksheet.write(i + 1, 11, staff['yield_enhanced_products_count'])
            worksheet.write(i + 1, 12, staff['equity_public_offering_count'])
            worksheet.write(i + 1, 13, staff['small_t_one_assets_count'])
            worksheet.write(i + 1, 14, staff['stock_financing_count'])
            worksheet.write(i + 1, 15, staff['more_t_one_assets_count'])
            worksheet.write(i + 1, 16, staff['Private_equity_products_count'])
            worksheet.write(i + 1, 17, staff['configure_China_count'])
            worksheet.write(i + 1, 18, staff['staff_score'])


        # 保存到内存
        import io
        f = io.BytesIO()
        workbook.save(f)
        f.seek(0)

        # 保存到磁盘
        #         # workbook.save('员工信息表.xls')

        # 响应
        from django.http import HttpResponse
        response = HttpResponse(f.getvalue())
        response['Content-Type'] = 'application/vnd.ms-excel'
        response['Content-Disposition'] = 'attachment;filename=员工信息表.xls'

        return response


def staff_delete(request):
    """删除员工"""
    res = {
        'status': True,
        'message': None,
    }
    if request.method == 'POST':
        user_delete_msg = request.body.decode('utf-8')
        user_delete_msg = json.loads(user_delete_msg)
        print(user_delete_msg)
        staff_num=user_delete_msg['staff_num']
        staff=models.StaffInfo.objects.filter(staff_num=staff_num).first()
        if not staff:
            res['status'] = False
            res['message'] = '该员工不存在'
            return JsonResponse(res)
        #获取该员工的id
        staff_id=staff.id
        print('staff_id',staff_id)

        staff.delete()

        return JsonResponse(res)

